package com.atao.baokede.RabbitMqListener;

import com.alipay.api.domain.Detail;
import com.atao.baokede.mapper.ItemOrderDetailMapper;
import com.atao.baokede.pojo.DetailOrder;
import com.atao.baokede.pojo.ItemOrder;
import com.atao.baokede.pojo.dto.DelayCartOrderDto;
import com.atao.baokede.service.CartService;
import com.atao.baokede.service.ItemOrderService;
import com.atao.baokede.service.ItemService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.atao.baokede.constant.OrderConstant.STATUS_PAID;
import static com.atao.baokede.constant.RabbitMqConstant.*;

@Component
public class OrderDelayQueue {
    @Autowired
    private ItemOrderService itemOrderService;
    @Autowired
    private CartService cartService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private ItemOrderDetailMapper itemOrderDetailMapper;

    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = DELAY_QUEUE_ORDER_NAME,durable = "true"),
            exchange = @Exchange(name = DELAY_EXCHANGE_NAME, delayed = "true"),
            key = DELAY_ROUTING_KEY
    ))
    public void listenOrderDelayMessage(Long orderId) {
        // 1、查询订单
        ItemOrder order = itemOrderService.selectByOrderNo(orderId);

        // 2、查询订单状态,判断是否已支付
        if(order == null || order.getStatus() != STATUS_PAID){
            return;
        }

        // 3、未支付，取消订单
        itemOrderService.cancelOrder(orderId);

        // 4、恢复库存
        DetailOrder detailOrder = itemOrderService.getItemDetail(orderId);

        itemService.addStock(detailOrder);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = DELAY_QUEUE_ORDER_NAME,durable = "true"),
            exchange = @Exchange(name = DELAY_EXCHANGE_NAME, delayed = "true"),
            key = DELAY_ROUTING_KEY2
    ))
    public void listenCartDelayMessage(DelayCartOrderDto delayCartOrderDto) {
        // 1、查询订单
        ItemOrder order = itemOrderService.selectByOrderNo(delayCartOrderDto.getOrderId());

        // 2、查询订单状态,判断是否已支付
        if(order == null || order.getStatus() != STATUS_PAID){
            return;
        }

        // 3、未支付，取消订单
        itemOrderService.cancelOrder(delayCartOrderDto.getOrderId());

        // 4、恢复库存
        List<DetailOrder> detailOrders = itemOrderDetailMapper.getItemDetails(delayCartOrderDto.getOrderId());

        itemService.addStocks(detailOrders);
    }

}